﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

public partial class Contacts : System.Web.UI.Page
{
    DataTable DTQuestions;
    int CurrentPage = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        btnBack.Text = ResourceManage.GetString("Back", "ru");
        btnBack1.Text = ResourceManage.GetString("Back", "ru");

        this.Page.ClientScript.RegisterOnSubmitStatement(
  this.GetType(),
  "AjaxHack",
  "for ( var i = 0; i < parent.frames.length; ++i ) if ( parent.frames[i].FCK ) parent.frames[i].FCK.UpdateLinkedField();"
  );
        if (!IsPostBack)
        {
            MultiView1.ActiveViewIndex=0;
            GetGeneralData();
            GetData();
            GetMailData();
        }
    }

    protected void btnAddDescription_Click(Object sender, EventArgs e)
    {
        PageHeaderData.SetPageKeywords(NewsType.Contacts, txtKeywords.Text);

        Dal.arParams.Clear();
        Dal.arParams.Add((int)NewsType.Contacts);
        Dal.arParams.Add(txtBrowserTitle.Text);
        Dal.arParams.Add(txtDescription.Text);
        Dal.ExecuteDBsp("Admin_AddCategoryDescription", Dal.arParams, true);
    }

    private void GetMailData()
    {
        ObjectDataSource ods = new ObjectDataSource();
        ods.ID = "ods" + 1;
        ods.EnablePaging = gvMails.AllowPaging; //the paging of ODS depends on the paging of the GridView
        ods.TypeName = "MyTableAdapter"; //be sure to prefix the namespace of your application !!! e.g. MyApp.MyTableAdapter

        ods.SelectMethod = "GetData";
        ods.SelectCountMethod = "VirtualItemCount";
        ods.StartRowIndexParameterName = "startRow";
        ods.MaximumRowsParameterName = "maxRows";
        ods.EnableViewState = false;

        ods.ObjectCreating += new ObjectDataSourceObjectEventHandler(ods_ObjectCreating);
        gvMails.DataSource = ods;
        gvMails.DataBind();

        //if (ddlPageNumber.Items.Count == 0 || GVTrivias.PageCount != ddlPageNumber.Items.Count)
        //{
        //    ddlPageNumber.Items.Clear();
        // for (int icount = 1; icount < gvNews.PageCount + 1; icount++)
        //   {
        ////        ListItem li = new ListItem(icount.ToString(), icount.ToString());
        ////        ddlPageNumber.Items.Add(li);
        //    }
        //    lblShowRecords.Text = string.Format(" {0} ", GVTrivias.PageCount);
        //}

    }

    private void ods_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        //calling a "parametered" constructor of my own TableAdapter and passing it to the ObjectInstance property 
        Dal.arParams.Clear();
        Dal.arParams.Add(CurrentPage);//Current Page
        Dal.arParams.Add(gvMails.PageSize);//PageSize
        Dal.arParams.Add(0);//PageSize
        DataSet DS = Dal.ExecuteDBspDS("Admin_GetAllMailsWPaging", Dal.arParams);

        if (DS != null)
        {
            if (DS.Tables.Count > 0)
            {
                MyTableAdapter tAdapter = new MyTableAdapter(DS.Tables[0]);
                e.ObjectInstance = tAdapter;
            }
            //and that'all there's to it !!
        }
    }

    private void GetGeneralData()
    {
        DataTable DT = Dal.ExecuteDBsp("usp_DefaultProperties", null);
        if(DT!=null)
            if (DT.Rows.Count > 0)
            {
                txtEmail.Text = DT.Rows[0]["siteDefaultMail"].ToString();
                txtContent.Text = DT.Rows[0]["conectUS"].ToString().Replace("<br />","\r\n");
            }
    }

    private void GetData()
    {
        DTQuestions = Dal.ExecuteDBsp("usp_GetContactQuestions");
        gvQuestions.DataSource = DTQuestions;
        gvQuestions.DataBind();
    }

    protected void btnEditPartner_Click(Object sender, CommandEventArgs e)
    {
        int iID;
        Int32.TryParse(e.CommandArgument.ToString(), out iID);

        Dal.arParams.Clear();
        Dal.arParams.Add(iID);

        DataTable DT = Dal.ExecuteDBsp("Admin_GetContactQuestionByID", Dal.arParams);

        if (DT != null)
            if (DT.Rows.Count > 0)
            {
                hfQuestion.Value = DT.Rows[0]["ID"].ToString();
                txtQuestion.Text = DT.Rows[0]["Question"].ToString();
            }
    }

    protected void gvPartners_ItemCommand(object source, CommandEventArgs e)
    {
        bool bChanged = false;
        Int32 rowID;
        Int32.TryParse(e.CommandArgument.ToString(), out rowID);
        Int32 rowIndex = 0;

        if (DTQuestions != null)
        {
            for (Int16 i = 0; i < DTQuestions.Rows.Count; i++)
            {
                if (DTQuestions.Rows[i]["ID"].Equals(rowID))
                {
                    rowIndex = i;
                    break;
                }
            }

            switch (e.CommandName)
            {
                case "MoveUp":
                    if (rowIndex > 0)
                    {
                        DTQuestions.Rows[rowIndex - 1]["orderID"] = rowIndex;
                        DTQuestions.Rows[rowIndex]["orderID"] = rowIndex - 1;
                        bChanged = true;
                    }
                    break;
                case "MoveDown":
                    if (rowIndex < DTQuestions.Rows.Count - 1)
                    {
                        DTQuestions.Rows[rowIndex + 1]["orderID"] = rowIndex;
                        DTQuestions.Rows[rowIndex]["orderID"] = rowIndex + 1;
                        bChanged = true;
                    }
                    break;
            }
            if (bChanged)
            {
                string sXml = string.Empty;
                for (int iCount = 0; iCount < DTQuestions.Rows.Count; iCount++)
                {
                    sXml += string.Format("<c id=\"{0}\" ord=\"{1}\"/>", DTQuestions.Rows[iCount]["ID"], DTQuestions.Rows[iCount]["orderID"]);
                }
                sXml = "<cs>" + sXml + "</cs>";

                Dal.arParams.Clear();
                Dal.arParams.Add(sXml);
                Dal.ExecuteDBsp("Admin_UpdateQuestionOrderID", Dal.arParams);

            }
        }
       GetData();
    }

    protected void btnAddQuestion_Click(object sender, EventArgs e)
    {
        int iID;
        Int32.TryParse(hfQuestion.Value, out iID);

        UpdateLink(iID, txtQuestion.Text.Trim(), false);
        txtQuestion.Text = string.Empty;
    }

    protected void btnDeletePartner_Click(Object sender, CommandEventArgs e)
    {
        int iLinkID;
        Int32.TryParse(e.CommandArgument.ToString(), out iLinkID);

        UpdateLink(iLinkID,"", true);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="iType">0 - partners , 1 - links</param>
    /// <param name="sText"></param>
    /// <param name="sLink"></param>
    private void UpdateLink(int iID, string sText, bool Delete)
    {
        Dal.arParams.Clear();
        Dal.arParams.Add(iID);
        Dal.arParams.Add(sText);
        Dal.arParams.Add(Delete);
        Dal.ExecuteDBsp("Admin_SetContactQuestion", Dal.arParams, true);
        GetData();
    }

    protected void gvQuestions_RowBound(object sender, GridViewRowEventArgs e)
    {
        AjaxControlToolkit.ConfirmButtonExtender cb = new AjaxControlToolkit.ConfirmButtonExtender();
        try
        {
            cb.TargetControlID = e.Row.FindControl("btnDeletePartner").ClientID.Replace("_", "$");
            cb.OnClientCancel = "CancelClick";
            cb.ConfirmText = "Вы уверены , что хотите удалить запись ?";
            e.Row.Cells[3].Controls.Add(cb);
        }
        catch { }
    }

    protected void btnSaveEmails_Click(object sender, EventArgs e)
    {
        Dal.arParams.Clear();
        Dal.arParams.Add(txtEmail.Text);
        Dal.arParams.Add(txtContent.Text.Replace("\r\n","<br />"));
        Dal.ExecuteDBsp("Admin_UpdateDefaultProperties", Dal.arParams,true);
    }

    protected void btnDeleteMail_Click(Object sender, CommandEventArgs e)
    {
        Int32 iMailID;
        Int32.TryParse(e.CommandArgument.ToString(), out iMailID);

        Dal.arParams.Clear();
        Dal.arParams.Add(iMailID);
        Dal.ExecuteDBsp("Admin_DeleteMailByID", Dal.arParams);
        GetMailData();
    }

    protected void btnViewMail_Click(Object sender, CommandEventArgs e)
    {
        MultiView1.ActiveViewIndex =1;
        Int32 iMailID;
        Int32.TryParse(e.CommandArgument.ToString(), out iMailID);

        Dal.arParams.Clear();
        Dal.arParams.Add(iMailID);
        DataTable dt=Dal.ExecuteDBsp("Admin_GetMailByID", Dal.arParams);
        if(dt!=null)
            if(dt.Rows.Count>0)
            {
                hfMailID.Value = dt.Rows[0]["ID"].ToString();
                ltViewMail.Text = dt.Rows[0]["body"].ToString();
            }
        btnAnswer.CommandArgument = iMailID.ToString();
    }

    protected void btnBack_Click(Object sender, EventArgs e)
    {
        MultiView1.ActiveViewIndex = 0;
    }

    protected void btnAnswer_Click(Object sender, EventArgs e)
    {
        int iMailID = Convert.ToInt32(((Button)sender).CommandArgument);
        btnSendMail.CommandArgument = iMailID.ToString();
        MultiView1.ActiveViewIndex = 2;
        Dal.arParams.Clear();
        Dal.arParams.Add(iMailID);
        DataTable dt = Dal.ExecuteDBsp("Admin_GetMailByID", Dal.arParams);
        if (dt != null)
            if (dt.Rows.Count > 0)
            {
                lblAnswerTo.Text+= dt.Rows[0]["FromName"].ToString();
            }
    }

    protected void btnSendMail_Click(Object sender, EventArgs e)
    {
        int iMailID=Convert.ToInt32(((Button)sender).CommandArgument);

        Dal.arParams.Clear();
        Dal.arParams.Add(iMailID);
        DataTable dt = Dal.ExecuteDBsp("Admin_GetMailByID", Dal.arParams);
        if (dt != null)
            if (dt.Rows.Count > 0)
            {
                string sToEmail= dt.Rows[0]["From"].ToString();

                StringBuilder sb = new StringBuilder();
                sb.Append("Вам пришло сообщение от Med Server.<br />");
                sb.AppendFormat("{0}<br />", edMail.Value);
                sb.Append("С уважением коллектив Med Server.");

                //SendMail
                Helper.SendEmail("admin@medserver.co.il", "Med Server", sToEmail, "Вам пришло сообщение от Med Server.", sb);
                
                Dal.arParams.Clear();
                Dal.arParams.Add(iMailID);
                Dal.ExecuteDBsp("Admin_SetAnsweredMail", Dal.arParams);
            }
        GetMailData();
        MultiView1.ActiveViewIndex = 0;
    }

    // ConfirmDelete
    protected void gvMails_RowBound(object sender, GridViewRowEventArgs e)
    {
        AjaxControlToolkit.ConfirmButtonExtender cb = new AjaxControlToolkit.ConfirmButtonExtender();
        try
        {
            cb.TargetControlID = e.Row.FindControl("btnDeleteMail").ClientID.Replace("_", "$");
            cb.OnClientCancel = "CancelClick";
            cb.ConfirmText = "Вы уверены , что хотите удалить запись ?";
            e.Row.Cells[6].Controls.Add(cb);
        }
        catch { }
    }
    
    protected void gvMails_PageindexChanging(object sender, GridViewPageEventArgs e)
    {
        CurrentPage = e.NewPageIndex + 1;
        gvMails.PageIndex = e.NewPageIndex;
        GetMailData();
    }
}
